<?php
namespace application\datatypes;
use application\datatypes\DataType;
use application\utilities\Utility;
use application\system\Permalink as SystemPermalink;
class Permalink extends DataType {
	public static $name = 'Permalink';
	public static $fields = array(array('columnType'=>'VARCHAR(100)'));
	
	public static function validate($field, $data, $results) {
		// If the content is a type that is accessible by URLs, generate a permalink from the title	
		$type = $data['content_type'];
		if(!getOption('c'.$type.'_inaccessible_url')) {
			if(!$data['content_permalink']) {
				$title = $data['content_title'];
				$unique = Utility::makeUniqueUrl($title);
			}
			else {
				$unique = $data['content_permalink'];
				// Check to make sure it's unique
				$contentCheck = DB()->getVar("SELECT `content_id` FROM `cn_content` WHERE `content_permalink`='$unique'");
				$tagCheck = DB()->getVar("SELECT `tag_id` FROM `cn_tags` WHERE `tag_permalink`='$unique'");
				$typeCheck = DB()->getVar("SELECT `ct_id` FROM `cn_content_types` WHERE `ct_permalink`='$unique'");
				if(($contentCheck && ($contentCheck != $data['content_id'])) || $tagCheck || $typeCheck) {
	
					$results['errors'][] = 'Content must have a unique permalink. ('.$contentCheck.' != '.$data['content_id'].')';
				}
				
				
			}
			
			$results['db_fields']['content_permalink'] = $unique;
		}
		
		return $results;
	}
	
	public static function display($formElements) {
		return;
		?>
		
		<fieldset class="single-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php if($description = $formElements['description']) : ?>
				<p class="form-description"><?=$description?></p>
			<?php endif;?>
			<?=$formElements['elements']['element']?>
			</section>
		</fieldset>
		<?php
	}
	
	public static function build($field, $data) {
		$value = ($_REQUEST[$field->cf_column]) ? $_REQUEST[$field->cf_column] : $data[$field->cf_column];
		$formElements = array('description'=>$field->cf_description, 'column'=>$field->cf_column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type, 'elements'=>array(
						'element'=>
							sprintf('<input type="text" value="%1$s" class="short-text" name="%2$s" id="%2$s"/>', $value, $field->cf_column)
						
		));
		return $formElements;

	
	}
	
	public static function editForm($field) {
		?>
		<div class="box-content">
			You can't edit an automatic field.
		</div>
			<?php
	}
	
	public static function prepareData($field, $data) {

		$permalink = SystemPermalink::buildContentPermalink($data['content_id']);
		return $permalink;
				
	}
	
}
?>